<script lang="ts" setup>

import type { UploadProps } from "element-plus"
import { documentSaveApi, documentAssociateApi, documentGetApi, documentDownloadApi } from "@@/apis/intelligent"
import { downloadFile } from "@/common/utils/fileUtils"
import wikiTree from "./wikiTree.vue"
import { ElMessage } from "element-plus"
import { onMounted, ref, nextTick, watch } from "vue"
import { defineProps } from 'vue';
import VueOfficePdf from '@vue-office/pdf'
import VueOfficeDocx from '@vue-office/docx'
const props = defineProps({
  id: {
    type: String,
    required: true
  },
  type: {
    type: String,
    required: true
  }
});
const fileDataList = ref([])
const isFile = ref<boolean>(true)
const loading = ref(false)
// wiki上传
const fileListW = ref<File[]>([])
const fileList = ref<File[]>([])
function handleBeforeUpd(file: File): boolean {
  fileList.value = [...fileList.value, file]
  return false
}
let fileChangeTimer: ReturnType<typeof setTimeout> | null = null
// 上传
const handleFileChange: UploadProps["onChange"] = (file: any, fileList: any) => {
  const fd = new FormData()
  // 每次触发前清除定时器
  if (fileChangeTimer) {
    clearTimeout(fileChangeTimer)
  }
  // 只保留最后一轮执行
  fileChangeTimer = setTimeout(() => {
    // 等待 DOM 更新完成
    nextTick(() => {
      fileList.forEach((item: any, index: any) => {
        fd.append(`insert_files[${index}].file`, item.raw)
      })
      fd.append("associate_id", props.id as string)
      fd.append("associate_type", props.type)
      documentSaveApi(fd).then((res) => {
        ElMessage.success("上传成功")
        getDocumentInfo() // 隐藏上传按钮并展示树状信息
      })
      // 这里处理最终的 fileList，比如上传、保存
    })
  }, 100)
}

// 获取文件
const pdfUrl = ref("")
const id = ref("")
const fileType = ref("")
id.value = props.id
// 根据业务id获取文档树状信息
async function getDocumentInfo() {
  loading.value = true
  try {
    const res = await documentAssociateApi(id.value)
    fileDataList.value = res.data
    // 上传&删除后加载第一个
    handleSelect(fileDataList.value[0])
    if (fileDataList.value.length > 0) {
      isFile.value = false
    } else {
      isFile.value = true
    }
  } catch (error) {
    console.error("获取 PDF 失败", error)
  } finally {
    loading.value = false
  }
  loading.value = false
}

// 选择文件名
async function handleSelect(item: any) {
  loading.value = true
  if (item.document_suffix === 'zip') {
    ElMessage.success('压缩包文件,只支持下载和删除')
  } else {
    try {
      // 使用原始API获取文档
      const res = await documentGetApi(item.document_id)
      // 由于我们在API中设置了responseType: "blob"，res.data应该已经是Blob对象
      const blobData = res.data

      // 确定文件MIME类型
      let mimeType = blobData.type || 'application/pdf'
      const fileName = item.document_file_name || item.document_file_path || ''

      if (fileName.toLowerCase().endsWith('.docx')) {
        mimeType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        fileType.value = 'docx'
      } else {
        mimeType = 'application/pdf'
        fileType.value = 'pdf'
      }

      // 确保Blob的MIME类型正确
      if (blobData.type !== mimeType) {
        // 创建新的具有正确MIME类型的Blob
        const blob = new Blob([blobData], { type: mimeType })
        // 为避免残留旧 URL，释放旧 blob URL
        if (pdfUrl.value) {
          URL.revokeObjectURL(pdfUrl.value)
        }

        // 创建新的URL并赋值
        const url = URL.createObjectURL(blob)
        // 确保DOM更新后再设置URL
        nextTick(() => {
          pdfUrl.value = url
        })
      }
    } catch (error: any) {
      pdfUrl.value = ''
      fileType.value = ''
    } finally {
      loading.value = false
    }
  }
}
// 删除文件
const handleDelete = (ids: string) => {
  const fd = new FormData()
  const removeFileIds = [ids]
  removeFileIds.forEach((id, index) => {
    fd.append(`remove_files[${index}]`, id)
  })
  // 继续加上你已有的关联参数
  fd.append("associate_id", props.id as string)
  fd.append("associate_type", props.type)
  // 调用接口
  documentSaveApi(fd).then((res: any) => {
    if (res.code === 200) {
      ElMessage.success(res.msg)
      getDocumentInfo()
    }

  })
}
// 下载文件
const handleDownload = (item: any) => {
  const params = {
    file_id: item.document_id,
  }
  documentDownloadApi(params).then((res) => {
    downloadFile(res)
  })
}

// PDF查看器配置
const pdfOptions = ref({
  // 确保使用最新的PDF.js worker
  workerSrc: 'https://cdn.jsdelivr.net/npm/pdfjs-dist@3.11.174/build/pdf.worker.min.js',
  cMapUrl: 'https://cdn.jsdelivr.net/npm/pdfjs-dist@3.11.174/cmaps/',
  cMapPacked: true
})

// pdf 渲染事件处理
const renderedHandler = () => {
  loading.value = false
}
const errorHandler = (error: any) => {
  loading.value = false
  ElMessage.error('PDF文档渲染失败：' + (error?.message || '未知错误'))
}
// word 渲染事件处理
const onRendered = () => {
  loading.value = false
}
const onError = (error: any) => {
  loading.value = false
  ElMessage.error('DOCX文档渲染失败：' + (error?.message || '未知错误'))
}
onMounted(() => {
  getDocumentInfo()
})
watch(
  () => props.id,
  () => {
    // getDocumentInfo()
  }
)

</script>

<template>
  <div class="wiki-wrapper">
    <div class="wikiUpload" v-if="isFile" v-loading="loading">
      <div>
        <el-icon>
          <DocumentCopy />
        </el-icon>
      </div>
      <div>欢迎使用 WiKi !</div>
      <div>WiKi 主要是您仓库的文档（说明，状态）等等</div>
      <el-upload :show-file-list="false" action="https://your-upload-api.com/upload" accept=".zip, .pdf, .doc , .docx"
        ref="upload" :file-list="fileListW" :multiple="true" :before-upload="handleBeforeUpd" :on-change="handleFileChange">
        <div style="font-size: 14px; margin-top: 20px !important; color: #00f3c7">
          上传Wiki文档
        </div>
      </el-upload>
    </div>
    <div class="show-pdf" v-else>
      <el-upload class="again-upload" :show-file-list="false" action="https://your-upload-api.com/upload" ref="upload"
        :file-list="fileListW" accept=".zip, .pdf, .doc , .docx" :multiple="true" :before-upload="handleBeforeUpd" :on-change="handleFileChange">
        <el-button type="success">
          上传
        </el-button>
      </el-upload>
      <div style="display: flex; height: 100%;">
        <div class="wiki-tree">
          <wikiTree :fileDataList="fileDataList" @select="handleSelect" @delete="handleDelete"
            @download="handleDownload" />
        </div>
        <div class="show-pdfOrdocx" v-if="pdfUrl">
          <vue-office-pdf v-if="fileType === 'pdf'" :src="pdfUrl" :style="{ height: '100%', width: '100%' }" :options="pdfOptions"
            @rendered="renderedHandler" @error="errorHandler" />
          <vue-office-docx v-else-if="fileType === 'docx'" :src="pdfUrl" :style="{ height: '100%', width: '100%' }" @rendered="onRendered"
            @error="onError" />
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.show-pdf {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.wiki-tree {
  width: 20%;
  flex: 0 0 20%;
  overflow: auto;
  height: calc(100vh - 300px)
}

.show-pdfOrdocx {
  flex: 1;
  overflow: auto;
  height: calc(100vh - 300px);
}

.wiki-tree::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

// 滚动条上的滚动滑块
.wiki-tree::-webkit-scrollbar-thumb {
  border-radius: 4px;
  background-color: #90939955;
}

.wiki-tree::-webkit-scrollbar-thumb:hover {
  background-color: #90939977;
}

.wiki-tree::-webkit-scrollbar-thumb:active {
  background-color: #90939999;
}

// 当同时有垂直滚动条和水平滚动条时交汇的部分
.wiki-tree::-webkit-scrollbar-corner {
  background-color: transparent;
}

.pdfViewer {
  flex: 1;
}

.wiki-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.wikiUpload {
  width: 700px;
  height: 274px;
  text-align: center;
  background: var(--el-bg-color);
  border: 1px solid #409eff;
  position: relative;
}

.wikiUpload div:nth-child(1) {
  margin-top: 41px;
  font-size: 52px;
}

.wikiUpload div:nth-child(2) {
  margin-top: 30px;
  color: #9fbfe3;
  font-size: 22px;
}

.wikiUpload div:nth-child(3) {
  margin-top: 12px;
  color: #9fbfe3;
  font-size: 14px;
}

.wiki-btn {
  font-size: 14px !important;
}

.again-upload {
  text-align: right;
  margin-bottom: var(--main-padding);
}
</style>
